package com.wnn.demo.model.news.controller;

import com.github.pagehelper.PageInfo;
import com.wnn.demo.domain.*;
import com.wnn.demo.model.news.service.NewsService;
import com.wnn.demo.model.system.service.UserService;
import com.wnn.demo.model.task.service.AccessoryService;
import com.wnn.demo.model.task.service.FeedbackService;
import com.wnn.demo.model.task.service.TaskService;
import com.wnn.demo.pojo.Result;
import com.wnn.demo.pojo.ResultCode;
import com.wnn.demo.utils.IdGen;
import com.wnn.demo.utils.IdWorker;
import com.wnn.demo.utils.PageUtil;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/news")
@AllArgsConstructor
public class NewsController {

	@Autowired
	private NewsService newsService;
	@Autowired
	private Accessory accessory;

	@Autowired
	private AccessoryService accessoryService;
	//private FeedbackService feedbackService;
	@Autowired
	private IdWorker idWorker;
	@Autowired
	private UserService userService;



	/**
	 * 封面上传----
	 * @param file
	 * @return
	 */
	@PostMapping("/uploapicture")
	public Result uploapicture(MultipartFile file){

//		文件名
		String fileName = file.getOriginalFilename();
//		System.out.println("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为：" + suffixName);
		// 文件上传后的路径
		String property = System.getProperty("user.dir");
//			String filePath = property+"/target/classes/picture/";
		String filePath = property+"/src/main/resources/public/picture/";
		String savePath = filePath+fileName;
		String path ="picture/" + fileName;
		File dest = new File(filePath + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);

		} catch (IOException e) {
			e.printStackTrace();
			return Result.error();
		}
		return new Result(ResultCode.OK,path);
	}

	/**
	 * 文件上传----
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public Result upload(MultipartFile file){

//		文件名
			String fileName = file.getOriginalFilename();
//		System.out.println("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为：" + suffixName);
			// 文件上传后的路径
			String property = System.getProperty("user.dir");
//			String filePath = property+"/target/classes/picture/";
			String filePath = property+"/src/main/resources/public/picture/";
			String savePath = filePath+fileName;
			String path ="picture/" + fileName;
			File dest = new File(filePath + fileName);
			// 检测是否存在目录
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				file.transferTo(dest);

			} catch (IOException e) {
				e.printStackTrace();
				return Result.error();
			}
		return new Result(ResultCode.OK,path);
	}

	/**
	 * 新建任务-----
	 * @param news
	 */
	@PostMapping("/newNews")
	public Result save(@RequestBody News news){

		String id = idWorker.nextId() + "";
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipal();
		User user = userService.findUserByName(username);
		news.setId(id);
		news.setApproveStatus(0);//设置草稿状态
		news.setIsDeleted(0);//设置标记未删除
		news.setCreateBy(username);
		news.setCreateTime(new Date());
		newsService.save(news);
		String hiddenFilePath = news.getHiddenFilePath();
		String[] split = hiddenFilePath.split(",");
		for (String s : split) {
			String idd = idWorker.nextId() + "";
			accessory.setId(idd);
			accessory.setAccessoryId(id);
			accessory.setFilePath(s);
			accessoryService.saveFile(accessory);
		}
		return Result.ok();
		// 获取文件名
	}

	/**
	 * 删除单个任务----
	 * @param id
	 */
	@DeleteMapping("/deletedOne/{id}")
	public Result deleted(@PathVariable(value ="id") String id){
		Integer i = newsService.deletedOne(id);
		if (i>0){
			return Result.ok();
		}
		return Result.error();
	}

	/**
	 * 删除附件---
	 * @param
	 */
	@PostMapping("/delFile/{id}")
	public Result delFile(@PathVariable(value ="id") String id){
		System.out.println("id");
		accessoryService.deletedOne(id);
		return Result.ok();
	}

	/**
	 * 修改新闻---------
	 * @param news
	 */
	@PutMapping("/updateNews/{id}")
	public Result updateNews(@PathVariable(value = "id") String id,@RequestBody News news){
		news.setId(id);
		news.setUpdateTime(new Date());
		newsService.update(news);
		//获取路径
		String hiddenFilePath = news.getHiddenFilePath();
		String[] split = hiddenFilePath.split(",");
		if (split[0] == null){
			List<Accessory> files = accessoryService.findFile(news.getId());
			if (files.size()>0){
				for (Accessory file1 : files) {
					for (String s : split) {
						if (!file1.getFilePath().equals(s)){
							String idd = idWorker.nextId() + "";
							accessory.setId(idd);
							accessory.setAccessoryId(news.getId());
							accessory.setFilePath(s);
							accessoryService.saveFile(accessory);
						}
					}
				}
			}else{
				for (String s : split) {
					String idd = idWorker.nextId() + "";
					accessory.setId(idd);
					accessory.setAccessoryId(news.getId());
					accessory.setFilePath(s);
					accessoryService.saveFile(accessory);
				}
			}
		}
		return Result.ok();
	}



	/**
	 * 草稿新闻列表--------
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/getnewNews")
	public Result findAll(String titles,String createBy,String startTime,String endTime ,@RequestParam(defaultValue = "1") Integer page,
						  @RequestParam(defaultValue = "10") Integer limit){
		PageInfo<News> pageInfo  = newsService.selectNewsAll(titles,createBy,startTime,endTime,page,limit);
		return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
	}

	/**
	 * 新闻审核列表---
	 * @param titles
	 * @param createBy
	 * @param endTime
	 * @param startTime
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/getAuditNews")
	public Result findAuditAll(String titles,String createBy,String startTime,String endTime ,@RequestParam(defaultValue = "1") Integer page,
						  @RequestParam(defaultValue = "10") Integer limit){
		PageInfo<News> pageInfo  = newsService.findAuditList(titles,createBy,startTime,endTime,page,limit);
		return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
	}

//	/**
//	 * 根据名称查询新闻
//	 * @param newsque
//	 * @return
//	 */
//	@RequestMapping("/selectNewByName")
//	public Result selectByName(@RequestBody Newsque newsque,@RequestParam(defaultValue = "1") Integer page,
//							   @RequestParam(defaultValue = "10") Integer limit){
//		PageInfo<News> pageInfo = newsService.selectNewByName(newsque,page,limit);
//		return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
//	}

	/**
	 * 新闻审核通过的列表---
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/getReleaseNews")
	public Result findReleaseNews(String titles,String createBy,String startTime,String endTime ,@RequestParam(defaultValue = "1") Integer page,
										  @RequestParam(defaultValue = "10") Integer limit){
		PageInfo<News> pageInfo  = newsService.findReleaseNews(titles,createBy,startTime,endTime,page,limit);
//		PageUtil<News> pageUtil = new PageUtil<>();
		return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
	}

	/**
	 * 提交审核新闻----
	 * @param id
	 */
    @PostMapping("/submit/{id}")
	public Result submit(@PathVariable(value ="id") String id){
		//news.setApproveStatus(1);
		//news.setApproveBeginTime(new Date());
		Integer i = newsService.submitId(id);
		System.out.println(i);
		if (i>0){
			return Result.ok();
		}else {
			return Result.error();
		}
	}

	/**
	 * 审核通过---
	 * @param id
	 */
	@PostMapping("/audit/{id}")
	public Result audit(@PathVariable(value ="id") String id){
        //news.setApproveStatus(2);
        //news.setApproveEndTime(new Date());
		//newsService.submit(news);
		Integer i = newsService.submit(id);
		if (i>0){
			return Result.ok();
		}else {
			return Result.error();
		}
	}

	/**
	 * 审核驳回----
	 * @param id
	 */
	@PostMapping("/notAudit/{id}")
	public Result notAudit(@PathVariable(value ="id") String id){
//		news.setApproveStatus(0);
//		news.setApproveEndTime(new Date());
		Integer i = newsService.back(id);
		if (i>0){
			return Result.ok();
		}else {
			return Result.error();
		}
	}



	/**
	 * 根据时间查询任务
	 * @param news
	 * @return
	 */
	@PostMapping("/selectByTime")
	public List<News> selectByTime(News news){
		List<News> news1 = newsService.selectByTime(news);
		return news1;
	}

	/**
	 * 查看新闻详情------
	 * @param news
	 * @return
	 */
	@GetMapping("/selectById")
	public News selectById(News news){
		News news1 = newsService.selectOne(news);
		List<Accessory> file = accessoryService.findFile(news.getId());
		news1.setAccessories(file);
		return news1;
	}
}

